//
//  APIServerError.swift
//  Yip
//
//  Created by bo wang on 2022/5/29.
//  Copyright © 2022 yip.com. All rights reserved.
//

import Foundation
import YYModel

@objc class APIServerError: NSObject, YYModel {
    @objc var message: String?
    @objc var param: String?
    @objc var location: String?
    @objc var value: String?
    
    @objc var errors: [APIServerError] = []
    
    @objc static func modelCustomPropertyMapper() -> [String: Any]? {
        [
            "message": ["msg", "message", "messages", "errors.msg", "errors.message", "errors.messages"],
            "param": ["param", "errors.param"],
            "location": ["location", "errors.location"],
            "value": ["value", "errors.value"]
        ]
    }
    
    @objc static func modelContainerPropertyGenericClass() -> [String: Any]? {
        ["errors": APIServerError.self]
    }
    
    @objc func modelCustomTransform(from dic: [AnyHashable: Any]) -> Bool {
        if !errors.isEmpty, message == nil {
            message = errors.compactMap({ $0.message }).joined(separator: " ")
            param = errors.first?.param
            location = errors.first?.param
            value = errors.first?.param
        }
        return true
    }
    
    convenience init(with message: String) {
        self.init()
        self.message = message
    }
    
    func message(forKey key: String) -> String? {
        key.lowercased() == (param ?? location)?.lowercased() ? message : nil
    }
}
